﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WxYygh.Common;
using WxYygh.Models.WeChatPay;
using WxYygh.ServiceReference2;

namespace WxYygh.Controllers
{
     [WeChatCheck]
    public class H5PayController : Controller
    {
        public static string wxJsApiParam { get; set; } //H5调起JS API参数
        // GET: H5Pay
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult H5Pay(string out_trade_no)
        {
           
            LogHelper.WriteLog("out_trade_no=" + out_trade_no);
            JsApiPay jsApiPay = new JsApiPay();
            double jkje = 0;
            string sql = string.Format(@" select * from ms_yygh t where out_trade_no ='{0}'", out_trade_no);

            DataSet dt = DbHelperSQL.Query(sql);

            if (dt.Tables[0].Rows.Count > 0)
            {
                ViewBag.brid = dt.Tables[0].Rows[0]["brid"].ToString();
                ViewBag.hyid = dt.Tables[0].Rows[0]["hyid"].ToString();

                jkje =double.Parse(dt.Tables[0].Rows[0]["ghf"].ToString());
                jsApiPay.total_fee = Convert.ToInt32(decimal.Parse(dt.Tables[0].Rows[0]["ghf"].ToString()) * 100);

            }
            else {
                jsApiPay.total_fee =0;

                return View();

            }

            jsApiPay.openid = Session["openid"].ToString();

            jsApiPay.body = "浙中医大二院-挂号缴费";

            LogHelper.WriteLog("jsApiPay=");
            WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(out_trade_no);
            wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数    
            ViewBag.wxJsApiParam = wxJsApiParam;

            ViewBag.out_trade_no = out_trade_no;
         
            

            ViewBag.fee = jkje;
            LogHelper.WriteLog("wxJsApiParam : " + wxJsApiParam);
            return View();
        }

        /// <summary>
        /// 设置预下单参数
        /// </summary>
        /// <returns></returns>
        public string GetJsApiParameters()
        {
            LogHelper.WriteLog("JsApiPay::GetJsApiParam is processing...");

            WxPayData jsApiParam = new WxPayData();
            jsApiParam.SetValue("appId", ConfigurationManager.AppSettings["appID"]);
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=123456789");
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            string parameters = jsApiParam.ToJson();

            LogHelper.WriteLog("Get jsApiParam : " + parameters);
            return parameters;
        }

        /// <summary>
        /// 查询订单状态
        /// </summary>
        /// <returns></returns>
        public string queryOrder(string out_trade_no, string brid, string hyid)
        {
            string result = "-1";

            WxPayData req = new WxPayData();
            req.SetValue("out_trade_no", out_trade_no);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                if (res.GetValue("trade_state").ToString() == "SUCCESS")
                {
                    ZJSXHYYServiceSoapClient service = new ZJSXHYYServiceSoapClient();


                    StringBuilder strXml = new StringBuilder();

                    strXml.Append("<?xml version='1.0' encoding='utf-8'?>");
                    strXml.Append("<data>");
                    strXml.AppendFormat("<funcode>{0}</funcode>", "500003");
                    strXml.AppendFormat("<outtradeno>{0}</outtradeno>", res.GetValue("transaction_id").ToString());
                    strXml.AppendFormat("<buyeraccount>{0}</buyeraccount>", "微信公众号");
                    strXml.AppendFormat("<outpayno>{0}</outpayno>", res.GetValue("out_trade_no").ToString());
                    strXml.AppendFormat("<opttype>{0}</opttype>", 3);
                    strXml.AppendFormat("<hyid>{0}</hyid>", hyid);
                    strXml.AppendFormat("<brid>{0}</brid>", brid);
                    strXml.AppendFormat("<fee>{0}</fee>", res.GetValue("total_fee").ToString());
                    strXml.AppendFormat("<jsjm>{0}</jsjm>", Session["openid"].ToString());
                    strXml.AppendFormat("<paymenttime>{0}</paymenttime>", DateTime.ParseExact(res.GetValue("time_end").ToString(), "yyyyMMddHHmmss", null));

                    strXml.Append("</data>");

                    string outputXml = string.Empty;
                    LogHelper.WriteLog("strxml2" + strXml.ToString());
                    int refXml = service.MainService(strXml.ToString(), ref outputXml);

                    result = refXml.ToString();
                }

            }

            return result;
        }

    }
}